package com.common.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.entity.sys.SysMenu;
import com.entity.sys.SysUser;
import com.entity.sys.query.SysQuery;
import com.service.sys.SysMenuService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class PermissionInterface implements StpInterface {

    @Resource
    private SysMenuService sysMenuService;



    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> list = new ArrayList<String>();
        // 2. 遍历角色列表，查询拥有的权限码
        for (String roleId : getRoleList(loginId, loginType)) {
            SysQuery queryVo = new SysQuery();
            queryVo.setId(Long.parseLong(roleId));
            //查询角色和权限(这里根据业务自行查询)
            List<SysMenu> menuList = sysMenuService.selectPermsByRoleId(queryVo);
            List<String> collect = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
            list.addAll(collect);
        }
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> list = new ArrayList<>();
        SysUser user = (SysUser) StpUtil.getSession().get("user");
        list.add(user.getRoleId().toString());
        return list;
    }
}
